package com.coai.file.repository

import com.coai.file.model.ChunkUploadRecord
import com.coai.file.model.FileCategory
import com.coai.file.model.FileMetadata
import com.coai.file.model.FileStatus
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository
import java.time.LocalDateTime

@Repository
interface FileMetadataRepository : JpaRepository<FileMetadata, String> {
    
    // 根据上传者查询文件
    fun findByUploaderIdOrderByCreatedAtDesc(
        uploaderId: String,
        pageable: Pageable
    ): List<FileMetadata>
    
    // 根据会话ID查询文件
    fun findByConversationIdOrderByCreatedAtDesc(
        conversationId: String,
        pageable: Pageable
    ): List<FileMetadata>
    
    // 根据分类和上传者查询
    fun findByUploaderIdAndCategoryOrderByCreatedAtDesc(
        uploaderId: String,
        category: FileCategory,
        pageable: Pageable
    ): List<FileMetadata>
    
    // 根据MD5查找文件（去重）
    fun findByMd5Hash(md5Hash: String): FileMetadata?
    
    // 查找过期文件
    fun findByExpiresAtBeforeAndStatus(
        time: LocalDateTime,
        status: FileStatus
    ): List<FileMetadata>
    
    // 统计用户存储使用量
    @Query("SELECT COALESCE(SUM(f.size), 0) FROM FileMetadata f WHERE f.uploaderId = :userId AND f.status != 'DELETED'")
    fun calculateUserStorageUsage(userId: String): Long
    
    // 统计会话文件数量
    fun countByConversationIdAndStatus(conversationId: String, status: FileStatus): Long
}

@Repository
interface ChunkUploadRecordRepository : JpaRepository<ChunkUploadRecord, String> {
    
    // 根据上传ID查找
    fun findByUploadId(uploadId: String): ChunkUploadRecord?
    
    // 查找过期的上传记录
    fun findByExpiresAtBeforeAndStatusNot(
        time: LocalDateTime,
        status: com.coai.file.model.ChunkUploadStatus
    ): List<ChunkUploadRecord>
    
    // 查找用户的上传记录
    fun findByUploaderIdOrderByCreatedAtDesc(
        uploaderId: String,
        pageable: Pageable
    ): List<ChunkUploadRecord>
}
